package com.example.onlinemonitoring.comCenter;

import com.example.onlinemonitoring.Util.CRC16;
import com.example.onlinemonitoring.Util.CommPortManager;
import com.example.onlinemonitoring.Util.HexUtil;
import com.example.onlinemonitoring.Util.IEEE754Utils;
import com.example.onlinemonitoring.model.Appdevice;
import com.example.onlinemonitoring.model.Gispdsensor;
import com.example.onlinemonitoring.serviceImpl.GispdsensorServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.context.annotation.Scope;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service("gispd61850Com")
@Scope("prototype")
public class Gispd61850Com extends CommPortManager {
    @Autowired
    private GispdsensorServiceImpl gispdserviceimpl;
    @Override
    public void receiveData(String str) {
        setText("收到sanway请求：" + str + "\r\n");
        Date dt = new Date();
        if (str.length() == 10){
            int startAddr = parseHex4(str.substring(2, 4));
            int addrLength = parseHex4(str.substring(4, 6));
            String s = "02";
            for (int i = startAddr; i < startAddr + addrLength; i++)
            {
                Gispdsensor gispd = new Gispdsensor();
                gispd.setStationid(ad.getStationid());
                gispd.setDevicegroup(ad.getDevicegroup());
                gispd.setDeviceaddr(i);
                gispd = gispdserviceimpl.getModel(gispd);
                if(gispd == null){
                    gispd = new Gispdsensor();
                }
                s += String.format("%02x", i);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                s += HexUtil.stringToAsciiTrim(sdf.format(dt));
                switch (isnull(gispd.getLastdischargetype()))
                {
                    case "颗粒放电": s += "00"; break;
                    case "间隙放电": s += "01"; break;
                    case "电晕放电": s += "02"; break;
                    case "电极放电": s += "03"; break;
                    case "空穴放电": s += "04"; break;
                    case "未知": s += "05"; break;
                    default: s += "00"; break;
                }
                s += String.format("%08X", isnull(gispd.getLastrst()));
                s += String.format("%08X", isnull(gispd.getLasttot()));
                s += IEEE754Utils.singleToHex(isnull(gispd.getLastdischargeamount()));
                s += String.format("%08X", isnull(gispd.getLastsignalpower()));
                if(isnull(gispd.getLastcommunicationstatus()) == 0){
                    s += String.format("%08X", 0);
                }else{
                    s += String.format("%08X", 1);
                }
            }
            s += CRC16.calcCrc16(s);
            Send(s);
        }
    }
}
